package io.codegeneratetool.core;

import java.io.Writer;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.MultiTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;

/** 初始化代码生成需要的环境,其中包含spring和freemark的部分操作
 * @author jifsu
 *  主要是初始化spring,和freemarker环境
 */
public final class Environment {
	 
	private static ApplicationContext context;
	private static Configuration configuration = null;
	protected static ConcurrentHashMap<String , Template> templates = new ConcurrentHashMap<String, Template>();
	public static void init() throws Exception { 
		if(context!=null){
			return;
		}
		 context = new ClassPathXmlApplicationContext("classpath:spring/applicationContext*.xml"); 
		 initFreemarker(); 
	}
	
	private  static void initFreemarker() throws Exception{
		configuration = new Configuration();
		configuration.setObjectWrapper(new DefaultObjectWrapper());  
		ClassTemplateLoader classTemplateLoader = new ClassTemplateLoader(Environment.class, "/");
		TemplateLoader loader = configuration .getTemplateLoader();
		TemplateLoader[] ls = new TemplateLoader[]{loader ,classTemplateLoader};
		MultiTemplateLoader mt = new MultiTemplateLoader(ls);
		
		configuration.setTemplateLoader(mt);
		//加载并设置freemarker.properties  
        Properties p = new Properties();  
        p.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("freemarker.properties"));  
        configuration.setSettings(p);  
	}
	
	/**
	 * 说明：处理模版,模版路径需要自己写,格式为 :  kjlink/wuxi/core/web/....xhtml  你懂得
	 * @author jiaxf 创建时间2013-5-13上午10:51:53
	 * @param 
	 */
	public static void processTemplate(String paramTemplate,Map<String, Object> dataModel,Writer out) throws Exception{
		 
		String string = "templates/"+paramTemplate;
		Template template =null;
		if(templates.containsKey(string)){ //如果有模版缓存
			template = templates.get(string);
		}else{ //否则去读取模版,并缓存 
			template =configuration.getTemplate(string);
			templates.put(string, template); 
		} 
		template.process(dataModel, out);
		out.flush(); 
	}
	
	public static  <T> T getBean(Class<T> clazz){
		return context.getBean(clazz);
	}
	
	public  static <T> T getBean(String beanId,Class<T> clazz){
		return context.getBean(beanId,clazz);
	}
	
	public static  Object getBean(String beanId){
		return context.getBean(beanId);
	}	
	
	
	
	
	
}
